package com.zmn.oms.zmn.business.impl.part;

import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import org.apache.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.json.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.constant.ExpressConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.log.FcPartLogBService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.messageV1.app.MessageSendAppService;
import com.zmn.oms.business.interfaces.part.OrderPartBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.fcorderpart.*;
import com.zmn.oms.model.dto.fcorderpart.expressage.ExpressageDTO;
import com.zmn.oms.model.dto.order.proxy.OrderLogDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderPartDIO;
import com.zmn.oms.model.dto.part.*;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.fcorderpart.*;
import com.zmn.oms.model.entity.fcorderpart.detail.FcOrderPartDetail;
import com.zmn.oms.model.entity.fcorderpart.detail.FcOrderPartPostDetail;
import com.zmn.oms.model.entity.log.FcPartLog;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.part.OrderPart;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.express.OrderPostService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.services.interfaces.order.OrderChangeService;
import com.zmn.oms.services.interfaces.part.OrderPartService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderFactoryPartBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.scm2.common.model.dro.scm.factory.goods.FactoryGoodsDRO;
import com.zmn.scm2.common.model.query.scm.factory.goods.FactoryGoodsQuery;
import com.zmn.scm2.dubbo.interfaces.scm.factory.goods.FactoryGoodsListRemoteService;
import com.zmn.tapi.dubbo.interfaces.expressage.ExpressageRemoteService;
import com.zmn.tapi.common.expressage.Expressage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：厂家配件业务实现类
 *
 * @author LiangHailong
 * @date 2019/05/15 16:05
 */
@Service
public class ZsOrderFactoryPartBServiceImpl implements ZsOrderFactoryPartBService {
    private Logger logger = LoggerFactory.getLogger(ZsOrderFactoryPartBServiceImpl.class);
    private static final String TAG = "言而有信-厂家配件业务";

    @Autowired
    OrderFactoryPartService orderFactoryPartService;
    @Autowired
    OrderFactoryService orderFactoryService;
    @Autowired
    OrderFactoryPartPostService orderFactoryPartPostService;
    @Autowired
    OrderPartService orderPartService;
    @Autowired
    OrderPartBService orderPartBService;
    @Autowired
    FcPartLogBService fcPartLogBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    ElasticSearchDataSyncService elasticSearchDataSyncService;
    @Autowired
    OrderPostService orderPostService;
    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    MessageSendAppService messageSendAppService;

//    @Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    protected FactoryListRemoteService factoryListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected FactoryGoodsListRemoteService factoryGoodsListRemoteService;
    @Reference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
    protected ExpressageRemoteService expressageRemoteService;


    @Override
    public ApplyFactoryPartCheckDTO applyFcPartCheck(Long orderId) throws OmsBaseException {
        ApplyFactoryPartCheckDTO applyCheckDTO = new ApplyFactoryPartCheckDTO();

        List<OrderFactoryPart> orderFactoryParts = orderFactoryPartService.listByOrderId(orderId);
        // 没有申请厂商配件，审核状态按审核成功算
        if (CollectionUtils.isEmpty(orderFactoryParts)) {
            applyCheckDTO.setReviewStatus(OrderConsts.REVIEW_STATUS_SUCCESS);
            return applyCheckDTO;
        }

        // 将配件按审核状态分类
        List<OrderFactoryPart> doing = new LinkedList<>();
        List<OrderFactoryPart> success = new LinkedList<>();
        List<OrderFactoryPart> fail = new LinkedList<>();
        for (OrderFactoryPart item : orderFactoryParts) {
            switch (item.getReviewStatus().intValue()) {
                case OrderConsts.REVIEW_STATUS_DOING:
                    doing.add(item);
                    break;
                case OrderConsts.REVIEW_STATUS_SUCCESS:
                    success.add(item);
                    break;
                case OrderConsts.REVIEW_STATUS_FAIL:
                    fail.add(item);
                    break;
            }
        }

        // 如果存在待审核配件，工单审核状态=待审核
        if (!doing.isEmpty()) {
            applyCheckDTO.setReviewStatus(OrderConsts.REVIEW_STATUS_DOING);
        }
        // 否则，如果存在审核成功配件，工单审核状态=审核成功
        else if (!success.isEmpty()) {
            applyCheckDTO.setReviewStatus(OrderConsts.REVIEW_STATUS_SUCCESS);
            applyCheckDTO.setReviewSuccessParts(success);
        }
        // 否则，如果存在审核失败配件，工单审核状态=审核失败
        else if (!fail.isEmpty()) {
            applyCheckDTO.setReviewStatus(OrderConsts.REVIEW_STATUS_FAIL);
        }
        else {
            throw new OmsBaseException(String.format("工单厂商配件审核状态异常，orderId:[%d]", orderId));
        }

        return applyCheckDTO;
    }

    /**
     * 申请厂家配件
     * @param orderFactoryPartDTO
     * @return
     */
    @Override
    @Transactional
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_PART_APPLY, beforeProceed = false)
    public void applyFcPart(OrderFactoryPartDTO orderFactoryPartDTO) throws OmsBaseException {

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderFactoryPartDTO.getOrderId(),
                orderFactoryPartDTO.getWorkId());
        if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)){
            throw new OmsBaseException("此工单已收单，不可操作配件");
        }

        if (CollectionUtils.isEmpty(orderFactoryPartDTO.getFactoryParts())) {
            throw new OmsBaseException("参数错误，不存在申请的配件");
        }
        Long orderId = orderFactoryPartDTO.getOrderId();
        OrderFactory orderFactory = orderFactoryService.findOrderFactoryByKey(orderId);
        if (orderFactory == null) {
            throw new OmsBaseException("未找到对应的厂商单信息");
        }
        // 更新厂商审核版本号，然后重新获取厂商信息
        Long fcOrderId = orderFactory.getFcOrderId();
        orderFactoryService.updateReviewByKey(fcOrderId);
        elasticSearchDataSyncService.syncWorkIndex(fcOrderId);   // 通知同步审核状态到es

        orderFactory = orderFactoryService.findOrderFactoryByKey(orderId);
        Integer reviewVersion = orderFactory.getPartReviewVersion();
        Integer factoryId = orderFactory.getFactoryId();

        // 厂商配件类型转换
        String masterName = orderFactoryPartDTO.getOperator();
        Date createTime = new Date();
        List<OrderFactoryPart> orderFactoryParts = new LinkedList<OrderFactoryPart>();
        orderFactoryPartDTO.getFactoryParts().forEach(item -> {
            OrderFactoryPart orderFactoryPart = new OrderFactoryPart();
            orderFactoryPart.setPartId(item.getPartId());
            orderFactoryPart.setNumber(item.getNumber());
            orderFactoryPart.setPicSrc1(item.getPicSrc1());
            orderFactoryPart.setPicSrc2(item.getPicSrc2());
            orderFactoryPart.setPicSrc3(item.getPicSrc3());
            orderFactoryPart.setApplyType(OrderFactoryPartConsts.ENGINEER_APPLY);

            orderFactoryPart.setCreater(masterName);
            orderFactoryPart.setCreateTime(createTime);
            orderFactoryPart.setMasterId(orderFactoryPartDTO.getOperatorId());
            orderFactoryPart.setMasterName(masterName);
            orderFactoryPart.setOrderId(orderFactoryPartDTO.getOrderId());
            orderFactoryPart.setFactoryId(factoryId);
            orderFactoryPart.setReviewVersion(reviewVersion);

            // 默认设置：配件类型=厂商配件，旧件返厂=未处理，审核状态=待审核
            orderFactoryPart.setSrc(OrderConsts.FC_PART_TYPE_FACTORY);
            orderFactoryPart.setRetrieve(GlobalConsts.NONE);
            orderFactoryPart.setReviewVersion(GlobalConsts.NONE);
            orderFactoryPart.setReviewStatus(OrderConsts.REVIEW_STATUS_DOING);

            orderFactoryParts.add(orderFactoryPart);
        });

        // 补充配件基本信息
        List<Integer> partIdList = orderFactoryParts.stream().map(OrderFactoryPart::getPartId).collect(Collectors.toList());
        // 从scm获取配件信息
        FactoryGoodsQuery query = FactoryGoodsQuery.builder().fcId(Long.valueOf(orderFactoryParts.get(0).getFactoryId())).idList(partIdList).build();
        logger.info("#insertOrder 获取厂商配件信息 入参：{}", JSON.toJSONString(query));
        ResponseDTO<List<FactoryGoodsDRO>> responseDTO = factoryGoodsListRemoteService.listFactoryGoods(query);
        logger.info("#insertOrder 获取厂商配件信息 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException("获取配件信息失败，请稍后重试");
        }

        List<FactoryGoodsDRO> dbParts = responseDTO.getData();
        for (OrderFactoryPart fcPart : orderFactoryParts) {
            boolean noFound = true;
            for (FactoryGoodsDRO partDRO : dbParts) {
                if (Objects.equals(fcPart.getPartId(), partDRO.getId() )) {
                    fcPart.setPartName(partDRO.getGoodsAlias());
                    fcPart.setUnit(partDRO.getUnitName());
                    fcPart.setPrice(null);    // 厂商配件默认不填价格
                    fcPart.setPartCode(partDRO.getGoodsId()); // 配件编码

                    fcPart.setCategId(partDRO.getCategTwoId());
                    fcPart.setCategName(partDRO.getCategTwoName());
                    fcPart.setCategOneId(partDRO.getCategOneId());
                    fcPart.setCategOneName(partDRO.getCategOneName());
                    StringBuilder partFullName = new StringBuilder();
                    partFullName.append(partDRO.getCategOneName());
                    partFullName.append("-");
                    partFullName.append(partDRO.getCategTwoName());
                    partFullName.append("-");
                    partFullName.append(partDRO.getGoodsAlias());
                    fcPart.setPartFullName(partFullName.toString());
                    fcPart.setPartName(partDRO.getGoodsAlias());

                    fcPart.setImgSrc1(partDRO.getImgSmallSrc());
                    fcPart.setImgSrc2(partDRO.getImgFrontSrc());
                    fcPart.setImgSrc3(partDRO.getImgSideSrc());

                    noFound = false;
                    break;
                }
            }
            if (noFound) {
                throw new OmsBaseException("配件不存在");
            }
        }

        orderFactoryPartService.addFactoryPartList(orderFactoryParts);

        // 添加操作日志(拦截器实现)
        StringBuilder sb = new StringBuilder("配件类型：厂商配件，配件：");
        for (OrderFactoryPart fcPart : orderFactoryParts) {
            sb.append(fcPart.getCategOneName()).append("-")
                    .append(fcPart.getCategName()).append("-").append(fcPart.getPartName())
                    .append("，数量：").append(fcPart.getNumber())
                    .append("；");
        }
        orderFactoryPartDTO.setOperatorLogRemark(sb.toString());

    }

    /**
     * 查询订单配件详情
     * @param fcOrderPartId
     * @return
     */
    @Override
    public FcOrderPartDetail detail(Integer fcOrderPartId) throws OmsBaseException {

        FcOrderPartDetail detail = new FcOrderPartDetail();
        // 配件详情
        OrderFactoryPart part = orderFactoryPartService.findByKey(fcOrderPartId);
        if (Objects.equals(part,null)){
            throw new OmsBaseException("配件不存在");
        }

        detail = BeanMapper.map(part, FcOrderPartDetail.class);
        // 配件物流信息
        List<OrderFactoryPartPost> partPostList = orderFactoryPartPostService.listByPartId(fcOrderPartId);
        List<FcOrderPartPostDetail> postDetailList = BeanMapper.mapList(partPostList, FcOrderPartPostDetail.class);

        detail.setPostInfo(postDetailList);

        // 日志
        List<FcPartLog> logList = fcPartLogBService.findLogsByFcPartId(fcOrderPartId);
        detail.setLogList(logList);

        return detail;
    }

    /**
     * 添加厂商的旧件返厂要求
     * @param fcOrderOldPartReturn
     */
    @Override
    @Transactional
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_OLD_PART_TO_FACTORY)
    public void saveOldPartReturn(FcOrderOldPartReturn fcOrderOldPartReturn) {

        Integer fcOrderPartId = fcOrderOldPartReturn.getFcOrderPartId();
        //一.更新配件信息
        OrderFactoryPart orderFactoryPart = new OrderFactoryPart();
        // 主键
        orderFactoryPart.setFcOrderPartId(fcOrderPartId);
        // 是否需要返厂
        orderFactoryPart.setRetrieve(fcOrderOldPartReturn.getRetrieve());

        orderFactoryPartService.update(orderFactoryPart);

        // 手动添加日志
        String content;
        //需要返厂
        if (Objects.equals(fcOrderOldPartReturn.getRetrieve(),GlobalConsts.YES)){
            String address = fcOrderOldPartReturn.getAddress();
            String[] addStr = address.split("-");
            content = String.format("返厂地址:%s,姓名:%s,电话:%s,指定快递公司:%s",addStr[0],addStr[1],addStr[2],StringUtils.isBlank(fcOrderOldPartReturn.getExpressCompany())?"未指定":fcOrderOldPartReturn.getExpressCompany());
        } else{
            content = "返厂地址:配件不需要返厂";
        }

        this.saveLog(orderFactoryPartService.findByKey(fcOrderPartId),OrderLogConsts.ORDER_LOG_TYPE_OLD_PART_TO_FACTORY,content);
        // 二.若旧件需要返厂,添加物流信息
        if (Objects.equals(fcOrderOldPartReturn.getRetrieve(),GlobalConsts.YES)){
            // 多次旧件返厂.只保留最新的记录
            orderFactoryPartPostService.deleteReturn(fcOrderPartId);

            OrderFactoryPartPost orderFactoryPartPost = new OrderFactoryPartPost();
            // 订单配件id
            orderFactoryPartPost.setFcOrderPartId(fcOrderPartId);
            // 设置为返厂
            orderFactoryPartPost.setFcOrderPartPostType(OrderConsts.FACTORY_PART_POST_TYPE_RETURN);
            // 订单id
            orderFactoryPartPost.setOrderId(fcOrderOldPartReturn.getOrderId());
            // 未发货
            orderFactoryPartPost.setStatus(GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT);
            String address = fcOrderOldPartReturn.getAddress();
            String[] addStr = address.split("-");
            // 邮寄地址
            orderFactoryPartPost.setAddress(StringUtils.isBlank(addStr[0])?"":addStr[0]);
            // 收货人姓名
            orderFactoryPartPost.setConsigneeName(StringUtils.isBlank(addStr[1])?"":addStr[1]);
            // 收货人电话
            orderFactoryPartPost.setConsigneePhone(StringUtils.isBlank(addStr[2])?"":addStr[2]);
            // 快递公司
            orderFactoryPartPost.setExpressCompany(fcOrderOldPartReturn.getExpressCompany());
            // 快递公司编号
            orderFactoryPartPost.setExpressCompanyCode(fcOrderOldPartReturn.getExpressCompanyCode());
            // 是否指定快递公司
            orderFactoryPartPost.setAssignExpressCompany(StringUtils.isBlank(fcOrderOldPartReturn.getExpressCompany())?GlobalConsts.NO:GlobalConsts.YES);

            orderFactoryPartPostService.insert(orderFactoryPartPost);
        }

    }

    /**
     * 厂家邮寄配件
     * @param fcOrderPartPost
     */
    @Override
    @Transactional
    public void savePartPost(FcOrderPartPost fcOrderPartPost) {
        // 更新配件信息 冗余信息 express_code
        OrderFactoryPart orderFactoryPart = new OrderFactoryPart();
        // 主键
        orderFactoryPart.setFcOrderPartId(fcOrderPartPost.getFcOrderPartId());

        //orderFactoryPartService.update(orderFactoryPart);

        // 删除审核成功时记录的配件邮寄记录 重新记录
        orderFactoryPartPostService.deleteSend(fcOrderPartPost.getFcOrderPartId());
        // 添加物流信息
        OrderFactoryPartPost orderFactoryPartPost = BeanMapper.map(fcOrderPartPost, OrderFactoryPartPost.class);
        // 已发货
        orderFactoryPartPost.setStatus(GlobalConsts.EXPRESS_POST_STATUS_TRANSIT);
        // 设置为邮寄
        orderFactoryPartPost.setFcOrderPartPostType(OrderConsts.FACTORY_PART_POST_TYPE_SEND);

        // 查询快递信息
        logger.info("#orderFactoryPart 查询物流信息 入参：{}, {}", orderFactoryPartPost.getExpressCompanyCode(),
                orderFactoryPartPost.getExpressCode());
        ResponseDTO<Expressage> responseExpressage = expressageRemoteService.getExpressageByCompanyAndCode(
                orderFactoryPartPost.getExpressCompanyCode(), orderFactoryPartPost.getExpressCode());
        logger.info("#orderFactoryPart 查询物流信息 出参：{}", JSON.toJSONString(responseExpressage));
        if (Objects.nonNull(responseExpressage.getData())) {
            Expressage expressageDRO = responseExpressage.getData();
            orderFactoryPartPost.setStatus(OrderPostConsts.getZmnPostStatus(expressageDRO.getState()));
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(expressageDRO.getList())) {
                orderFactoryPartPost.setExpressData(com.alibaba.fastjson.JSON.toJSONString(expressageDRO.getList()));
            }
        }

        orderFactoryPartPostService.insert(orderFactoryPartPost);

        // 手动记录一条日志
        String  content = String.format("邮寄地址:%s,姓名:%s,电话:%s,快递公司:%s",fcOrderPartPost.getAddress(),fcOrderPartPost.getConsigneeName(),fcOrderPartPost.getConsigneePhone(),fcOrderPartPost.getExpressCompany());
        this.saveLog(orderFactoryPart,OrderLogConsts.ORDER_LOG_TYPE_PART_POST,content);

        // 订阅快递单号,实时追踪状态
        com.zmn.common.dto2.ResponseDTO responseDTO = expressageRemoteService.subscribe(orderFactoryPartPost.getExpressCompanyCode(), orderFactoryPartPost.getExpressCode());
        logger.info("[{}] 订阅结果：{}",TAG,responseDTO.getMessage());

        // 邮寄给用户,发送短信
        String phone = fcOrderPartPost.getConsigneePhone();
        if (StringUtil.isMobile(phone) && Objects.equals(OrderConsts.FACTORY_PART_POST_TO_USER,fcOrderPartPost.getPostAddressType())){
            // 配件信息
            OrderFactoryPart part = orderFactoryPartService.findByKey(fcOrderPartPost.getFcOrderPartId());
            // 短信文本
            String text = String.format("【言而有信售后平台】 尊敬的用户, 工程师申请的厂商配件:%s, 已经邮寄, 快递单号:%s, 请您及时关注物流信息。如有问题请联系:4000665315",part.getPartFullName(),fcOrderPartPost.getExpressCode());
            //MQPushUtil.sendBizSmsInfo(phone,text); 2019-12-26 需求暂时删除
        }
    }

    /**
     * 配件撤回
     * @param fcOrderPartId
     */
    @Override
    @Transactional
    public void recall(Integer fcOrderPartId,Long orderId) {
        // 删除配件信息
        orderFactoryPartService.deleteByKey(fcOrderPartId);
        // 删除配件物流信息
        orderFactoryPartPostService.deleteByFcOrderPartId(fcOrderPartId);
        // 重新填入工单配件
        List<OrderPart> orderParts = BeanMapper.mapList(this.getReviewSuccessPart(orderId), OrderPart.class); //获取该工单所有审核通过的配件
        AddOrderPartDTO addOrderPartDTO = new AddOrderPartDTO();
        addOrderPartDTO.setOrderId(orderId);
        addOrderPartDTO.setParts(orderParts);
        orderPartBService.insertFactoryOrderPart(addOrderPartDTO);
    }

    /**
     * 获取物流配件
     * @param orderId
     * @return
     */
    @Override
    public FcOrderPartRespDTO getExpressParts(Long orderId) throws OmsBaseException {
        FcOrderPartRespDTO respDTO = new FcOrderPartRespDTO();

        List<FcOrderPartDTO> list = new LinkedList();
        respDTO.setList(list);
        respDTO.setPartsSrc(OrderConsts.FC_PART_TYPE_FACTORY);

        FcOrderPartCheckDTO check = orderFactoryPartService.doFactoryPartCheck(orderId);
        if (check.isContainsFcPart() && check.isContainsFcPartPost()) {
            // 构建查找器：邮寄信息(包含返厂和邮寄信息)
            Map<Integer, List<OrderFactoryPartPost>> finder = Maps.newHashMap();
            check.getOrderFactoryPartPosts().forEach(post -> {
                List<OrderFactoryPartPost> postList = finder.get(post.getFcOrderPartId());
                if (postList == null) {
                    postList = new LinkedList();
                    finder.put(post.getFcOrderPartId(), postList);
                }
                postList.add(post);
            });

            // 查询配件对应的物流信息
            for (OrderFactoryPart part : check.getOrderFactoryParts()) {
                // 非审核成功的配件不显示物流信息
                if (!Objects.equals(part.getReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS)) {
                    continue;
                }

                List<OrderFactoryPartPost> postList = finder.get(part.getFcOrderPartId());
                for (OrderFactoryPartPost post : postList) {
                    FcOrderPartDTO fcOrderPartDTO = this.convert2FcOrderPartDTO(part, post);
                    list.add(fcOrderPartDTO);
                }
            }
        }

        return respDTO;
    }

    /**
     * 用于查询快件物流信息，转换成FcOrderPartDTO
     */
    private FcOrderPartDTO convert2FcOrderPartDTO(OrderFactoryPart part, OrderFactoryPartPost partPost) {
        FcOrderPartDTO dto = BeanMapper.map(part, FcOrderPartDTO.class);
        dto.setPartPostId(partPost.getPostId());
        dto.setFcOrderPartPostType(partPost.getFcOrderPartPostType());
        dto.setPostAddressType(partPost.getPostAddressType());
        dto.setPostStatus(partPost.getStatus());
        dto.setAssignExpressCompany(partPost.getAssignExpressCompany());
        dto.setExpressCompany(partPost.getExpressCompany());
        dto.setExpressCompanyCode(partPost.getExpressCompanyCode());

        String expressCode = partPost.getExpressCode();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(expressCode)) {
            dto.setExpressCode(expressCode);
            dto.setExpressUrl(ExpressConsts.EXPRESS_QUERY_URL + expressCode.trim());
        }

        return dto;
    }

    /**
     * 修改旧件返厂信息，转换成FactoryPartDTO
     */
    private FactoryPartDTO convert2FactoryPartDTO(OrderFactoryPart part, OrderFactoryPartPost partPost) {
        FactoryPartDTO dto = BeanMapper.map(part, FactoryPartDTO.class);
        dto.setPostId(partPost.getPostId());
        dto.setAddress(partPost.getAddress());
        dto.setConsigneeName(partPost.getConsigneeName());
        dto.setConsigneePhone(partPost.getConsigneePhone());
        dto.setExpressCode(partPost.getExpressCode());
        dto.setExpressCompany(partPost.getExpressCompany());
        dto.setExpressCompanyCode(partPost.getExpressCompanyCode());
        dto.setAssignExpressCompany(partPost.getAssignExpressCompany());
        dto.setRemark(partPost.getRemark());

        return dto;
    }

    /**
     * 工程师获取需要返厂的旧配件(不包含已向厂商邮寄出去的配件)
     * @param omsOperator
     * @return
     * @throws Exception
     */
    @Override
    public List<FactoryPartDTO> getToPostReturnFcPart(OmsOperator omsOperator){
        List<FactoryPartDTO> result = new LinkedList();

        List<OrderFactoryPartPost> orderFactoryPartPosts = this.getToPostReturnFcPartPost(omsOperator.getOrderId());
        if (CollectionUtils.isEmpty(orderFactoryPartPosts)) {
            return result;
        }

        // 转换成FactoryPartDTO，并补充配件信息
        List<OrderFactoryPart> partList = orderFactoryPartService.listByOrderId(omsOperator.getOrderId());
        for (OrderFactoryPartPost post : orderFactoryPartPosts) {
            for (OrderFactoryPart part : partList) {
                if (Objects.equals(part.getFcOrderPartId(), post.getFcOrderPartId())) {
                    FactoryPartDTO dto = BeanMapper.map(part, FactoryPartDTO.class);
                    dto.setPostId(post.getPostId());
                    dto.setAddress(post.getAddress());
                    dto.setConsigneeName(post.getConsigneeName());
                    dto.setConsigneePhone(post.getConsigneePhone());
                    dto.setExpressCompany(post.getExpressCompany());
                    dto.setExpressCompanyCode(post.getExpressCompanyCode());
                    dto.setAssignExpressCompany(post.getAssignExpressCompany());
                    dto.setRemark(post.getRemark());

                    result.add(dto);
                }
            }
        }

        return result;
    }

    /**
     * 邮寄配件（旧件返厂）
     * @param factoryPartPostDTO
     * @throws Exception
     */
    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_OLD_PART_POST, beforeProceed = false)
    public void updatePostReturnFcPart(FactoryPartPostDTO factoryPartPostDTO) throws OmsBaseException {
        doUpdatePostReturnFcPart(factoryPartPostDTO);
    }


    @Override
    @Transactional
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_OLD_PART_POST, beforeProceed = false)
    public void updateOldPostFcPart(OrderPartPostListDTO partPostListDTO) {
        StringBuilder expressCodeStr = new StringBuilder();

        try {
            List<OrderPartPostDTO> partPostList = partPostListDTO.getPartPostList();
            for (OrderPartPostDTO partPostDIO : partPostList) {
                FactoryPartPostDTO factoryPartPostDTO = BeanMapper.map(partPostDIO, FactoryPartPostDTO.class);
                factoryPartPostDTO.setPartPostIds(Lists.newArrayList(partPostDIO.getPostId().toString()));
                factoryPartPostDTO.setOrderId(partPostListDTO.getOrderId());
                factoryPartPostDTO.setWorkId(partPostListDTO.getWorkId());
                factoryPartPostDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SERVICEPROVIDER);
                factoryPartPostDTO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SERVICEPROVIDER) + "-" + partPostListDTO.getOperator());
                this.doUpdatePostReturnFcPart(factoryPartPostDTO);

                //发送快递单号信息
                expressCodeStr.append(partPostDIO.getExpressCode());
                expressCodeStr.append(",");
            }

           /* OrderFactory orderFactory = orderFactoryService.findOrderFactoryByKey(partPostListDTO.getOrderId());

            ResponseDTO<FactoryDRO> result = factoryListRemoteService.getFactoryById(orderFactory.getFactoryId());

            if (result.isSuccess()) {
                FactoryDRO factoryDRO = result.getData();
                String phone = factoryDRO.getMobile();
                if (StringUtil.isMobile(phone)){
                    String msg = String.format("工单%s的旧件已经邮寄，快递单号：%s，您可登录系统查看物流信息",
                            partPostListDTO.getOrderId(), expressCodeStr.substring(0, expressCodeStr.length() - 1));
                    //2019-12-26 需求暂时删除
                    //  MQPushUtil.sendBizSmsInfo(phone, String.format("【言而有信售后平台】您好，%s。如有疑问请拨打商务合作热线：400-0665-315" +，感谢您对言而有信售后平台的支持与信任！", msg));
                }
            } else {
                logger.info(String.format("【邮寄旧件】短信通知发送失败，%s", result.getMessage()));
            }*/

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void doUpdatePostReturnFcPart(FactoryPartPostDTO factoryPartPostDTO) throws OmsBaseException {
        List<OrderFactoryPartPost> orderFactoryPartPosts = orderFactoryPartPostService.listByPostIds(factoryPartPostDTO.getPartPostIds());
        if (orderFactoryPartPosts == null || orderFactoryPartPosts.isEmpty()) {
            throw new OmsBaseException("没有对应的旧件返厂信息。");
        }

        // 通过快递公司编号补全快递公司名称
        if (StringUtil.isBlank(factoryPartPostDTO.getExpressCompany())) {
            expressageRemoteService.listCompany().getData().stream().filter(item -> Objects.equals(factoryPartPostDTO.getExpressCompanyCode(), item.getCode())).findFirst().ifPresent(expressageCompany -> factoryPartPostDTO.setExpressCompany(expressageCompany.getName()));
        }

        // 修改已填写的邮寄记录，如果邮寄了多个配件（即多个配件打包成一个快递寄出），需保证该包裹中所有配件的快递单号同步修改。
        // 修改已填写的邮寄记录的判定条件为：只有一个postId，且post记录的状态是“已发货”
        if (factoryPartPostDTO.getPartPostIds().size() == 1
                && Objects.equals(GlobalConsts.EXPRESS_POST_STATUS_TRANSIT, orderFactoryPartPosts.get(0).getStatus())) {
            OrderFactoryPartPost post = orderFactoryPartPosts.get(0);
            String expressCode = post.getExpressCode();
            List<OrderFactoryPartPost> allPostList = orderFactoryPartPostService.listByOrderId(post.getOrderId());
            List<OrderFactoryPartPost> collect = allPostList.stream()
                    .filter(item -> expressCode.equals(item.getExpressCode()))
                    .collect(Collectors.toList());
            orderFactoryPartPosts = collect;
        }

        // 查询快递信息
        logger.info("#orderFactoryPart 查询物流信息 入参：{}, {}", factoryPartPostDTO.getExpressCompanyCode(),
                factoryPartPostDTO.getExpressCode());
        ResponseDTO<Expressage> responseExpressage = expressageRemoteService.getExpressageByCompanyAndCode(
                factoryPartPostDTO.getExpressCompanyCode(), factoryPartPostDTO.getExpressCode());
        logger.info("#orderFactoryPart 查询物流信息 出参：{}", JSON.toJSONString(responseExpressage));

        Date expressTime = new Date();
        for (OrderFactoryPartPost item : orderFactoryPartPosts) {
            // 首次填写邮寄记录， 变更发货状态
            if (Objects.equals(item.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT)) {
                item.setStatus(GlobalConsts.EXPRESS_POST_STATUS_TRANSIT); // 状态 -> 已发货
            }
            // 修改已填写过的邮寄记录，需保证邮寄状态为“已发货”
            else if (!Objects.equals(GlobalConsts.EXPRESS_POST_STATUS_TRANSIT, item.getStatus())) {
                throw new OmsBaseException("返厂配件不是未发货/已发货状态。");
            }

            item.setExpressCode(factoryPartPostDTO.getExpressCode());
            item.setExpressTime(expressTime);
            // 厂家没有指定快递公司的，设置快递公司
            if (Objects.equals(item.getAssignExpressCompany(), GlobalConsts.NO)) {
                item.setExpressCompanyCode(factoryPartPostDTO.getExpressCompanyCode());
                item.setExpressCompany(factoryPartPostDTO.getExpressCompany());
            }
            if (StringUtils.isNotBlank(factoryPartPostDTO.getRemark())) {
                item.setRemark(factoryPartPostDTO.getRemark().trim());
            }

            if (Objects.nonNull(responseExpressage.getData())) {
                Expressage expressageDRO = responseExpressage.getData();
                item.setStatus(OrderPostConsts.getZmnPostStatus(expressageDRO.getState()));
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(expressageDRO.getList())) {
                    item.setExpressData(com.alibaba.fastjson.JSON.toJSONString(expressageDRO.getList()));
                }
            }
            orderFactoryPartPostService.updateExpressById(orderFactoryPartPosts);

        }
        // 订阅快递单号,实时追踪状态s
        expressageRemoteService.subscribe(factoryPartPostDTO.getExpressCompanyCode(), factoryPartPostDTO.getExpressCode());
    }

    /**
     * 清除厂商单配件信息
     * @param orderId
     */
    @Override
    @Transactional
    public void deleteAllParts(Long orderId) {

        // 查询工程师申请的配件
        List<Integer> list = orderFactoryPartService.listIdPartByOrderIdAndApplyType(orderId,
                OrderFactoryPartConsts.ENGINEER_APPLY);

        if (CollectionUtil.isNotNullOrEmpty(list)){
            // 厂商配件信息删除，删除工程师申请配件
            orderFactoryPartService.deleteByFcOrderPartIds(list);
            // 配件物流信息删除，删除工程师申请配件的物流
            orderFactoryPartPostService.deleteByFcOrderPartIds(list);
        }

        // 工单配件信息删除
        orderPartService.deleteByOrderIdAndPartType(orderId,OrderConsts.PART_TYPE_FACTORY);
    }

    /**
     * 更新快递邮寄状态
     * @param expressageDTO
     */
    @Override
    public void updatePostStatus(ExpressageDTO expressageDTO) {
        Integer state = expressageDTO.getState();
        String code = expressageDTO.getCode();
        OrderFactoryPartPost post = orderFactoryPartPostService.findOrderIdByExpressCodeAndExpressCompanyCode(code, expressageDTO.getCompany());
        if (state != null && StringUtils.isNotBlank(code)){
            Integer status = OrderConsts.getPostStatusByState(expressageDTO.getState());
            OrderFactoryPartPost orderFactoryPartPost = new OrderFactoryPartPost();
            orderFactoryPartPost.setExpressCode(code);
            orderFactoryPartPost.setStatus(status);
            orderFactoryPartPost.setExpressData(JSON.toJSONString(expressageDTO.getList()));
            orderFactoryPartPostService.updatePostStatus(orderFactoryPartPost);
        }

        // 发送签收push推送
        if (Objects.equals(state, OrderConsts.KUAIDI_100_TRANSIT) && !Objects.equals(post.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_RECEIPT)) {
            OrderWork orderWork = orderWorkService.findOrderWorkByKey(post.getOrderId(), post.getOrderId());
            // 已领单已上门 进行中 的工单 快递物流签收后推送消息给师傅
            List<Integer> supportBStatusList = Arrays.asList(OrderStatusConsts.WORK_STATUS_TAKE, OrderStatusConsts.WORK_STATUS_VISIT);
            if (supportBStatusList.contains(orderWork.getStatus()) && Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
                Map<String, Object> params = Maps.newHashMap();
                params.put("order_id", String.valueOf(post.getOrderId()));
                params.put("work_id", String.valueOf(post.getOrderId()));
                params.put("biz_type", String.valueOf(orderWork.getBizType()));
                messageSendAppService.pushAppMessageInfo(MessageRuleIdConsts.PUSH_MSG_RULEID_POST_EXPRESS, JSON.toJSONString(params), orderWork);
            }
        }

    }

    /**
     * 获取待审核状态的厂商配件
     * @param orderId
     * @return
     */
    @Override
    public List<OrderFactoryPart> getWaiting4ReviewPart(Long orderId) {
        List<OrderFactoryPart> orderFactoryParts = orderFactoryPartService.listByOrderId(orderId);

        List<OrderFactoryPart> collect = orderFactoryParts.stream()
                .filter(item -> (Objects.equals(OrderConsts.REVIEW_STATUS_DOING, item.getReviewStatus())))
                .collect(Collectors.toList());

        return collect;
    }

    /**
     * 获取审核成功状态的厂商配件
     * @param orderId
     * @return
     */
    @Override
    public List<OrderFactoryPart> getReviewSuccessPart(Long orderId) {
        List<OrderFactoryPart> orderFactoryParts = orderFactoryPartService.listByOrderId(orderId);

        List<OrderFactoryPart> collect = orderFactoryParts.stream()
                .filter(item -> (Objects.equals(OrderConsts.REVIEW_STATUS_SUCCESS, item.getReviewStatus())))
                .collect(Collectors.toList());

        return collect;
    }

    /**
     * 获取需要旧件返厂但尚未邮寄的配件邮寄基础信息
     * @param orderId
     * @return
     */
    @Override
    public List<OrderFactoryPartPost> getToPostReturnFcPartPost(Long orderId) {
        List<OrderFactoryPartPost> orderFactoryPartPosts = orderFactoryPartPostService.listByOrderId(orderId);
        List<OrderFactoryPartPost> collect = orderFactoryPartPosts.stream()
                .filter(item ->
                     Objects.equals(OrderConsts.FACTORY_PART_POST_TYPE_RETURN, item.getFcOrderPartPostType())
                        && Objects.equals(GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT, item.getStatus())
                )
                .collect(Collectors.toList());

        return collect;
    }

    /**
     * 判断是否含有待审核状态的厂商配件，有返回true
     * @param orderId
     * @return
     */
    @Override
    public boolean containsWaiting4ReviewPart(Long orderId) {
        List<OrderFactoryPart> orderFactoryParts = this.getWaiting4ReviewPart(orderId);
        return CollectionUtils.isNotEmpty(orderFactoryParts);
    }

    /**
     * 判断是否含有需要旧件返厂但尚未邮寄的邮寄的配件，有返回true
     * @param orderId
     * @return
     */
    @Override
    public boolean containsToPostReturnFcPart(Long orderId) {
        List<OrderFactoryPartPost> list = this.getToPostReturnFcPartPost(orderId);
        return CollectionUtils.isNotEmpty(list);
    }

    /**
     * 通过工单厂商配件ID查物流信息，用于工程师端修改配件邮寄信息前的信息查询
     * @param fcOrderPartId
     * @return
     */
    @Override
    public FactoryPartDTO getExpressPartById(Integer fcOrderPartId) throws OmsBaseException {
        OrderFactoryPart orderFactoryPart = orderFactoryPartService.findByKey(fcOrderPartId);
        List<OrderFactoryPartPost> postList = orderFactoryPartPostService.findByFcOrderPartId(fcOrderPartId);

        if (orderFactoryPart == null || CollectionUtils.isEmpty(postList)) {
            throw new OmsBaseException("未找到工单厂商配件物流信息");
        }

        for (OrderFactoryPartPost post: postList) {
            if (Objects.equals(OrderConsts.FACTORY_PART_POST_TYPE_RETURN, post.getFcOrderPartPostType())) {
                return this.convert2FactoryPartDTO(orderFactoryPart, post);
            }
        }
        throw new OmsBaseException("未找到工单厂商配件物流信息");
    }

    /**
     * 查询订单待审核配件
     * @param orderId
     * @return
     */
    @Override
    public List<OrderFactoryPart> findParts4Review(Long orderId) {
        OrderFactory orderFactory = orderFactoryService.findOrderFactoryByKey(orderId);
        FcOrderPartQuery query = new FcOrderPartQuery();
        query.setOrderId(orderId);
        query.setReviewStatus(OrderConsts.REVIEW_STATUS_DOING);
        query.setReviewVersion(orderFactory.getPartReviewVersion());
        return orderFactoryPartService.listByQuery(query);
    }

    /**
     * 保存配件审核
     * @param fcOrderPartReview
     */
    @Override
    @Transactional
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_PART_REVIEW, beforeProceed = false)
    public void savePartsReview(FcOrderPartReview fcOrderPartReview) {
        List<OrderFactoryPart> parts = fcOrderPartReview.getParts();

        Long orderId = parts.get(0).getOrderId();
        // 确认本次审核结果
        Integer reviewResult = OrderConsts.REVIEW_STATUS_FAIL;
        List<OrderFactoryPart> factoryParts = parts.stream().filter(e -> Objects.equals(e.getReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS)).collect(Collectors.toList());
        if (factoryParts.size()>0){
            reviewResult = OrderConsts.REVIEW_STATUS_SUCCESS;

            // 审核通过的配件,记录一条邮寄配件的物流信息
            factoryParts.forEach(e ->{
                OrderFactoryPartPost orderFactoryPartPost = new OrderFactoryPartPost();
                orderFactoryPartPost.setOrderId(e.getOrderId());
                orderFactoryPartPost.setFcOrderPartId(e.getFcOrderPartId());
                // 待发货
                orderFactoryPartPost.setStatus(GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT);
                // 设置为邮寄
                orderFactoryPartPost.setFcOrderPartPostType(OrderConsts.FACTORY_PART_POST_TYPE_SEND);
                orderFactoryPartPostService.insert(orderFactoryPartPost);
            });

        }

        // 更新明细的审核状态
        parts.forEach(e -> {
            e.setReviewTime(new Date());
            orderFactoryPartService.update(e);

            OrderFactoryPart orderFactoryPart = orderFactoryPartService.findByKey(e.getFcOrderPartId());
            // 手动记录log
            StringBuilder log = new StringBuilder();
            log.append(String.format("配件名称: %s ,数量 %s%s,", orderFactoryPart.getPartName(), orderFactoryPart.getNumber(), orderFactoryPart.getUnit()));
            if (StringUtil.isNotBlank(orderFactoryPart.getImgSrc1())) {
                log.append(String.format(",工程师拍照:[{{img:%s}}]", orderFactoryPart.getImgSrc1()));
            }
            if (StringUtil.isNotBlank(orderFactoryPart.getImgSrc2())) {
                log.append(String.format(",[{{img:%s}}]", orderFactoryPart.getImgSrc2()));
            }
            if (StringUtil.isNotBlank(orderFactoryPart.getImgSrc3())) {
                log.append(String.format(",[{{img:%s}}]", orderFactoryPart.getImgSrc3()));
            }
            log.append("审核结果:");
            if (Objects.equals(e.getReviewStatus(), OrderConsts.REVIEW_STATUS_FAIL)) {
                log.append("失败。");
            } else if (Objects.equals(e.getReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS)){
                log.append("成功。");
            }
            this.saveLog(e,OrderLogConsts.ORDER_LOG_TYPE_PART_REVIEW,log.toString());
        });

        // 更新工单的配件审核状态
        this.updateOrderPartReview(orderId,reviewResult);

        // 新增工单厂商配件
        /*if (Objects.equals(reviewResult,OrderConsts.REVIEW_STATUS_SUCCESS)){
            List<OrderPart> orderParts = BeanMapper.mapList(this.getReviewSuccessPart(orderId), OrderPart.class); //获取该工单所有审核通过的配件
            AddOrderPartDTO addOrderPartDTO = new AddOrderPartDTO();
            addOrderPartDTO.setOrderId(orderId);
            addOrderPartDTO.setParts(orderParts);
            orderPartBService.insertFactoryOrderPart(addOrderPartDTO);
        }*/
        // 组装log
        parts.forEach(e -> {
            OrderFactoryPart part = orderFactoryPartService.findByKey(e.getFcOrderPartId());
            BeanMapper.copy(part, e);
        });

    }

    /**
     * 手动添加厂商单配件日志
     * @param orderFactoryPart
     * @param logType
     */
    private void saveLog(OrderFactoryPart orderFactoryPart,Integer logType,String content){
        FcPartLog fcPartLog = new FcPartLog();

        fcPartLog.setFcOrderPartId(orderFactoryPart.getFcOrderPartId());
        //Integer logType = OrderLogConsts.ORDER_LOG_TYPE_PART_REVIEW;
        fcPartLog.setType(logType);
        fcPartLog.setTypeName(OrderLogConsts.getOrderLogTypeName(logType));
        fcPartLog.setOperator("商户");
        fcPartLog.setOperatorId((long)GlobalConsts.OPERATE_USER_TYPE_FACTORY);
        fcPartLog.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_FACTORY);

        StringBuilder log = new StringBuilder("厂商配件:");
        log.append(content);
        fcPartLog.setContent(log.toString());

        fcPartLogBService.save(fcPartLog);
    }

    /**
     * 更新厂商工单配件审核状态
     */
    private void updateOrderPartReview(Long orderId,Integer reviewResult){
        OrderFactory orderFactory = new OrderFactory();
        orderFactory.setFcPartReviewStatus(reviewResult);
        orderFactory.setFcOrderId(orderId);
        orderFactoryService.updateByKey(orderFactory);
    }

    /**
     *
     */
    /**
     * 添加日志
     *
     * @param orderId
     * @param orderLogDTO
     */
    private void saveOrderLo(Long orderId, OrderLogDTO orderLogDTO) {
        if (orderLogDTO.getType() == null) {
            return;
        }

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setWorkId(orderId);
        orderLog.setType(orderLogDTO.getType());
        orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(orderLogDTO.getType()));
        orderLog.setBeforeStatus(orderWork.getStatus());
        orderLog.setBeforeStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setBeforeResultStatus(orderWork.getResultStatus());
        orderLog.setBeforeResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        orderLog.setAfterStatus(orderWork.getStatus());
        orderLog.setAfterStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setAfterResultStatus(orderWork.getResultStatus());
        orderLog.setAfterResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        OrderWorkLogUtils.processOrderLogOperater(orderLog, orderLogDTO);

        StringBuilder sb = new StringBuilder();

        if (org.apache.commons.lang3.StringUtils.isNotBlank(orderLogDTO.getOperatorRemark())) {
            sb.append(orderLogDTO.getOperatorRemark());
        }

        if (org.apache.commons.lang3.StringUtils.isNotBlank(orderLogDTO.getOperatorLogRemark())) {
            sb.append(orderLogDTO.getOperatorLogRemark());
        }

        orderLog.setContent(sb.toString());
        orderLogBService.save(orderLog);
    }

    @Override
    public void insertPartListAndPost(List<FactoryNewOrderPartDIO> partDIOS) throws OmsBaseException {
        if (CollectionUtil.isNullOrEmpty(partDIOS)) {
            return;
        }
        // region begin 封装处理配件、物流信息

        // 从scm获取配件信息
        List<Integer> partids = partDIOS.stream().map(FactoryNewOrderPartDIO::getPartId).collect(Collectors.toList());
        FactoryGoodsQuery query = FactoryGoodsQuery.builder().fcId(Long.valueOf(partDIOS.get(0).getFactoryId())).idList(partids).build();
        logger.info("#insertOrder 获取厂商配件信息 入参：{}", JSON.toJSONString(query));
        ResponseDTO<List<FactoryGoodsDRO>> responseDTO = factoryGoodsListRemoteService.listFactoryGoods(query);
        logger.info("#insertOrder 获取厂商配件信息 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            throw new OmsBaseException("获取配件信息失败，请稍后重试");
        }
        Map<Integer, FactoryGoodsDRO> partMap = responseDTO.getData().stream().collect(Collectors.toMap(FactoryGoodsDRO::getId, factoryGoodsDRO -> {
            return factoryGoodsDRO;
        }));

        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(partDIOS.get(0).getOrderId());

        partDIOS.stream().forEach(partDIO -> {
            OrderFactoryPart part = BeanMapper.map(partDIO, OrderFactoryPart.class);
            part.setSrc(1);

            // scm中获取的配件信息
            FactoryGoodsDRO goods = partMap.get(part.getPartId());
            part.setCategOneId(goods.getCategOneId());
            part.setCategOneName(goods.getCategOneName());
            part.setCategId(goods.getCategTwoId());
            part.setCategName(goods.getCategTwoName());
            StringBuilder partFullName = new StringBuilder();
            partFullName.append(goods.getCategOneName());
            partFullName.append("-");
            partFullName.append(goods.getCategTwoName());
            partFullName.append("-");
            partFullName.append(goods.getGoodsAlias());
            part.setPartFullName(partFullName.toString());
            part.setPartName(goods.getGoodsAlias());
            part.setUnit(goods.getUnitName());
            part.setPartCode(goods.getGoodsId());

            part.setImgSrc1(goods.getImgSmallSrc());
            part.setImgSrc2(goods.getImgFrontSrc());
            part.setImgSrc3(goods.getImgSideSrc());

            part.setMasterId(Long.valueOf(GlobalConsts.NONE));
            part.setMasterName("");
            part.setPicSrc1("");

            Date currDate = DateUtil.getNow();

            part.setReviewStatus(2);
            part.setReviewTime(currDate);
            part.setRetrieve(GlobalConsts.NO);
            part.setReviewVersion(GlobalConsts.NONE);

            part.setCreater(partDIO.getOperator());
            part.setCreateTime(currDate);

            // 分开插入获取数据库生成的ID
            orderFactoryPartService.addFactoryPart(part);

            OrderFactoryPartPost partPost = new OrderFactoryPartPost();
            partPost.setFcOrderPartId(part.getFcOrderPartId());
            partPost.setOrderId(part.getOrderId());
            partPost.setFcOrderPartPostType(1);
            partPost.setStatus(1);
            partPost.setExpressCode(partDIO.getExpressCode());
            partPost.setExpressCompany(partDIO.getExpressCompany());
            partPost.setExpressCompanyCode(partDIO.getExpressCompanyCode());
            partPost.setAssignExpressCompany(1);
            Integer postTarget = partDIO.getPostTarget();
            partPost.setPostAddressType(postTarget);
            if (Objects.equals(OrderFactoryPartConsts.POST_YEYX_ADDRESS, postTarget)) {
                partPost.setConsigneeName("言而有信公司");
                partPost.setConsigneePhone("4000665315");
                partPost.setAddress("重庆市-渝北区-互联网产业园二期8号楼12层");
            } else {
                partPost.setConsigneeName(orderDetail.getUserName());
                partPost.setConsigneePhone(orderDetail.getTelephone());
                partPost.setAddress(String.format("%s%s%s%s", orderDetail.getProvinceName(), orderDetail.getCityName(), orderDetail.getCountyName(), orderDetail.getAddress()));
            }


            partPost.setCreater(partDIO.getOperator());
            partPost.setCreateTime(currDate);

            // 查询快递信息
            logger.info("#orderFactoryPart 查询物流信息 入参：{}, {}", partPost.getExpressCompanyCode(), partPost.getExpressCode());
            ResponseDTO<Expressage> responseExpressage = expressageRemoteService.getExpressageByCompanyAndCode(
                    partPost.getExpressCompanyCode(), partPost.getExpressCode());
            logger.info("#orderFactoryPart 查询物流信息 出参：{}", JSON.toJSONString(responseExpressage));
            if (Objects.nonNull(responseExpressage.getData())) {
                Expressage expressageDRO = responseExpressage.getData();
                partPost.setStatus(OrderPostConsts.getZmnPostStatus(expressageDRO.getState()));
                if (CollectionUtils.isNotEmpty(expressageDRO.getList())) {
                    partPost.setExpressData(com.alibaba.fastjson.JSON.toJSONString(expressageDRO.getList()));
                }
            }

            orderFactoryPartPostService.insert(partPost);
        });

    }
}
